package com.net.xpay.common.validator;

import com.google.common.base.Strings;
import com.net.xpay.common.domain.SiteConfig;
import com.net.xpay.common.manager.SiteConfigManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.common.exception.BusinessException;
import com.net.common.util.SerializationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SiteConfigValidator {
    @Autowired
    private SiteConfigManager siteConfigManager;

    public void validateAddSiteConfig(SiteConfig siteConfig) {
        log.info("validateAddSiteConfig params={}|siteConfigId={}", SerializationUtil.obj2String(siteConfig), siteConfig.getId());
        validateCommon(siteConfig);

        //验证数据库里是否已存在一条记录
        long count = siteConfigManager.count(new SiteConfig());

        if (count > 0) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "数据库中已有网站配置信息");
        }
    }

    public void validateUpdateSiteConfig(SiteConfig siteConfig) {
        log.info("validateUpdateSiteConfig params={}|siteConfigId={}", SerializationUtil.obj2String(siteConfig), siteConfig.getId());
        validateCommon(siteConfig);

        //id不为空
        if (siteConfig.getId() == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "id不能为空");
        }
    }

    public void validateCommon(SiteConfig siteConfig) {
        //验证网站名
        if (Strings.isNullOrEmpty(siteConfig.getName())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "网站名称不能为空");
        }
    }
}
